package edu.fight.config.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.fight.dto.JwtUser;
import edu.fight.dto.Result;
import edu.fight.dto.ResultStatus;
import edu.fight.utils.jwt.JwtUtils;
import edu.fight.utils.jwt.RsaFileInMemory;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;

@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Result res = null;
        // 获取请求头中令牌
        String token = request.getHeader("token");
        PublicKey publicKey = RsaFileInMemory.getPublicKey();
        try {
            JwtUser user = JwtUtils.getInfoFromToken(token, publicKey);
            return true;
            //ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException
        }catch (ExpiredJwtException e){
            e.printStackTrace();
            log.error(e.getMessage(),e);
            res = Result.to(ResultStatus.error, "令牌超时", null, e.getMessage());
        }catch (UnsupportedJwtException e){
            e.printStackTrace();
            log.error(e.getMessage(),e);
            res = Result.to(ResultStatus.error, "不支持的令牌协议", null, e.getMessage());
        }catch (MalformedJwtException e){
            e.printStackTrace();
            log.error(e.getMessage(),e);
            res = Result.to(ResultStatus.error, "令牌格式错误", null, e.getMessage());
        }catch (SignatureException e){
            e.printStackTrace();
            log.error(e.getMessage(),e);
            res = Result.to(ResultStatus.error, "令牌签名错误", null, e.getMessage());
        }catch (IllegalArgumentException e){
            e.printStackTrace();
            log.error(e.getMessage(),e);
            res = Result.to(ResultStatus.error, "参数非法", null, e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage(),e);
            res = Result.to(ResultStatus.error, e.getMessage(), null, null);
        }
        String resp = new ObjectMapper().writeValueAsString(res);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(resp);
        return false;
    }
}
